package impl

import (
	"blog/config"
	"blog/internal/common"
	"blog/internal/models"
	"blog/internal/pkg/cache"
	"blog/internal/pkg/password"
	"blog/internal/repository"
	"blog/pkg/utils/jwt"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"time"
)

type UserService struct {
	repo        repository.IUserRepository
	profileRepo repository.IProfileRepository
}

func NewUserService(r repository.IUserRepository, profile repository.IProfileRepository) *UserService {
	return &UserService{
		repo:        r,
		profileRepo: profile,
	}
}

// Login 登陆账号
func (s *UserService) Login(ctx *gin.Context, username, pwd string) (string, error) {

	// 根据用户名查找用户
	user, err := s.repo.FindByUsername(username)
	if err != nil {
		return "", errors.New("不存在该用户")
	}
	// 判断用户名密码
	if check := password.VerifyPassword(pwd, user.Password); !check {
		return "", errors.New("用户名密码错误")
	}
	cfg := config.GetConfig()
	token, err := jwt.GenerateToken(user.ID, user.Username, cfg.Jwt.Secret, cfg.Jwt.Expiration)
	if err != nil {
		return "", errors.New("服务器内部错误,请联系管理员")
	}

	err = cache.Set(ctx, fmt.Sprintf(common.LoginToken, user.ID), token, 24*time.Hour)

	if err != nil {
		log.Println("缓存TOKEN失败", err.Error())
	}
	// 更新最后一次登录IP和时间
	now := time.Now()
	user.LastLoginAt = &now
	user.LastLoginIP = ctx.ClientIP()
	err = s.repo.UpdateLastLogin(user)
	if err != nil {
		log.Println("更新最后一次登录时间失败:", err)
	}
	return token, nil
}

func (s *UserService) Logout(ctx *gin.Context, userId uint64) error {
	return cache.Rm(ctx, fmt.Sprintf(common.LoginToken, userId))
}

// Info 获取个人资料
func (s *UserService) Info(ctx *gin.Context, uid uint64) (*models.Profile, error) {

	profile, err := s.profileRepo.FindByUid(uid)
	if err != nil {
		return nil, err
	}
	return profile, nil
}
